#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "cJSON.h"

int main(int argc, char **argv)
{
    cJSON *root;
    cJSON *obj1;
    cJSON *obj12;
    char *result;               // 获取到的 JSON 字符串
    int length;                 // 获取到的 JSON 字符串的长度
    char *name = "test.json";   // 输入的 JSON 文件名
    FILE *fp;                   // 输入的 JSON 文件
    int len;                    // 实际读取文件中的数据长度

    cJSON *obj12_id;
    cJSON *obj12_val;
    cJSON *obj12_name;

    /* 打开JSON文件 */
    fp = fopen(name, "rb");
    if (!fp)
    {
        printf("err: open %s file failed!\r\n", name);
        return -1;
    }

    /* 偏移到文件最后, 查询当前偏移值则为文件大小 */
    fseek(fp, 0L, SEEK_END);
    length = ftell(fp);

    /* 偏移回文件头 */
    fseek(fp, 0L, SEEK_SET);
    result = malloc(length);
    len = fread(result, 1, length, fp);
    if(len != length)
    {
        printf("err: %s read failed! len = %d, length = %d\r\n", name, (int)len, length);
        return -1;
    }

    // printf("result = %s\r\n", result);

    root = cJSON_Parse(result);
    obj1 = cJSON_GetObjectItem(root, "obj_1");
    obj12 = cJSON_GetObjectItem(obj1, "obj_12");
    obj12_id = cJSON_GetObjectItem(obj12, "id");
    obj12_name = cJSON_GetObjectItem(obj12, "name");
    obj12_val = cJSON_GetObjectItem(obj12, "val");

    printf("id      = %d\r\n", obj12_id->valueint);
    printf("name    = %s\r\n", obj12_name->valuestring);
    printf("val     = %d\r\n", obj12_val->valueint);

    cJSON_Delete(root);
    fclose(fp);

    return 0;
}